package treenode;

/**
 * [3,9,20,null,null,15,7]
 * @author lizy4
 * @className TreeNode
 * @date 2021/5/11 23:45
 * @description
 */
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode() {
        left = null;
        right = null;
    }
    TreeNode(int val) {
        this.val = val;
        left = null;
        right = null;
    }

    public static TreeNode CreateTree(int[] array){
        TreeNode treeNode = new TreeNode();
        if (array == null){
            array = new int[]{6,3,2,5,4,1,8,7,9};
        }
        for (int i = 0; i < array.length; i++) {
            CreateTree(array[i], treeNode);
        }
        return treeNode;
    }



    public static void CreateTree(int val, TreeNode tree){
        // 如果当前二叉树是空的，拿第一个元素做头节点
        if (tree.getVal()==0){
            tree.setVal(val);
        }
        // 小放左，相等暂时不用管
        if (tree.getVal()>val){
            if (tree.getLeft()==null){
                // 如果左节点空，直接设置
                TreeNode leftTree = new TreeNode();
                leftTree.setVal(val);
                tree.setLeft(leftTree);
            } else if (tree.getLeft()!=null){
                // 如果左节点不为空，递归调用继续找左节点数据比较大小
                CreateTree(val, tree.getLeft());
            }
        }
        // 大放右，相等暂时不用管
        if (tree.getVal()<val){
            if (tree.getRight()==null){
                TreeNode rightTree = new TreeNode();
                rightTree.setVal(val);
                tree.setRight(rightTree);
            } else if (tree.getRight()!=null){
                CreateTree(val, tree.getRight());
            }
        }
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "val=" + val +
                ", left=" + left +
                ", right=" + right +
                '}';
    }
}